package com.xuanxing123.dao.hibernate;

import com.xuanxing123.dao.ProductDao;
import com.xuanxing123.model.Product;
import org.hibernate.Session;
import org.hibernate.HibernateException;
import org.springframework.stereotype.Repository;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.util.List;
import java.sql.SQLException;

@Repository("productDao")
public class ProductDaoHibernate extends GenericDaoHibernate<Product, Long> implements ProductDao {

    public ProductDaoHibernate() {
        super(Product.class);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<Product> getProductsByType(final Long typeId, final Integer count) {
        final String hql = "from Product where productType.id = " + typeId + " order by position";

        if (count <= 0) {
            return getHibernateTemplate().find(hql);
        } else {
            return getHibernateTemplate().executeFind(
                    new HibernateCallback() {
                        public Object doInHibernate(Session session) throws HibernateException, SQLException {
                            return session.createQuery(hql).setFirstResult(0).setMaxResults(count).list();
                        }
                    }
            );
        }
    }
}
